//
//  HHCoinViewController.m
//  WeCommunity
//
//  Created by HappyMilk 01 on 2017/8/10.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "HHCoinViewController.h"


#define PRODUCT_ID_30_COINS @"com.baisi.BIcommunity01"
#define PRODUCT_ID_200_COINS @"com.baisi.BIcommunity02"
#define PRODUCT_ID_REMOVE_AD @"com.baisi.BIcommunity03"

@interface HHCoinViewController ()
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (weak, nonatomic) IBOutlet UILabel *myCoinLabel;

@property (weak, nonatomic) IBOutlet UILabel *removeADLabel;

@property (weak, nonatomic) IBOutlet UILabel *zuanJiFenLabel;
@property (weak, nonatomic) IBOutlet UIButton *seeADBtn;
@property (weak, nonatomic) IBOutlet UILabel *seeADLabel;


@property (nonatomic, copy) NSString *productID;

@property (nonatomic, assign) BOOL shouldRewardUser;//观看广告成功
@end

@implementation HHCoinViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
    
    
    [self initViews];
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];//监听购买
    
    [GADRewardBasedVideoAd sharedInstance].delegate = self;
    [[GADRewardBasedVideoAd sharedInstance] loadRequest:[GADRequest request]
                                           withAdUnitID:@"ca-app-pub-1438263689659228/6329445499"];//激励视频广告
    
    

}

-(void)initViews{
    if(IS_CHINESE == false){
        _titleLabel.text = @"coins";
        [_cancelBtn setTitle:@"cancel" forState:0];

        _zuanJiFenLabel.hidden = true;
        _seeADBtn.hidden = true;
        _seeADLabel.hidden = true;
    }
    [self refreshViews];
}

-(void)refreshViews{
    int coins = [[UserInfoManger shared].contact.coins intValue];
    
    if([UserInfoManger shared].isRemovedAD){
        _removeADLabel.text = HH_LOC_STR(@"Purchased");
    }
    if(IS_CHINESE){
        _myCoinLabel.text = [NSString stringWithFormat:@"我的积分：%d积分",coins];
    }else{
        _myCoinLabel.text = [NSString stringWithFormat:@"My coins: %d",coins];
    }
    
}

- (IBAction)onBuy30Coins:(id)sender {
    
    if([self checkCanMakePayment]){
        SHOW_HUD(@"");
        _productID = PRODUCT_ID_30_COINS;
        [self requestProductData:_productID];
    }
    
}

- (IBAction)onBuy200Coins:(id)sender {
    if([self checkCanMakePayment]){
        SHOW_HUD(@"");
        _productID = PRODUCT_ID_200_COINS;
        [self requestProductData:_productID];
    }
}

//去广告
- (IBAction)onBuyRemoveAD:(id)sender {
    
    if([UserInfoManger shared].isRemovedAD){
        
        SHOW_HUD_MESSAGE(HH_LOC_STR(@"You have already purchased this item without having to buy it again"));
        return ;
    }
    
    
    if([self checkCanMakePayment]){
        SHOW_HUD(@"");
        _productID = PRODUCT_ID_REMOVE_AD;
        [self requestProductData:_productID];
    }
    
}

//恢复购买
- (IBAction)onRestore:(id)sender {
    SHOW_HUD(@"");
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}






#pragma mark - app内购
-(BOOL)checkCanMakePayment{
    if([SKPaymentQueue canMakePayments]){
        return YES;
    }else{
        UIAlertController *alertController=[UIAlertController alertControllerWithTitle:KNSLocal(@"alertTitle") message:HH_LOC_STR(@"Please turn on in-app paid purchase!") preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertAction=[UIAlertAction actionWithTitle:KNSLocal(@"alertOK") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertController addAction:alertAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    
    return NO;
}

#pragma mark - 请求商品
-(void)requestProductData:(NSString *)productID{
    NSSet *set = [NSSet setWithObjects:productID, nil];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
    request.delegate = self;
    [request start];
}

#pragma mark 收到产品返回信息
-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    NSArray *products = response.products;
    if([products count] == 0){
        NSLog(@"--------------没有商品------------------");
        HIDE_HUD;
        SHOW_HUD_MESSAGE(HH_LOC_STR(@"transaction failed!"));
        return;
    }
    
    SKProduct *p = nil;
    
    for (SKProduct *pro in products) {
        NSLog(@"pro info");
        NSLog(@"SKProduct 描述信息：%@", [pro description]);
        NSLog(@"localizedTitle 产品标题：%@", [pro localizedTitle]);
        NSLog(@"localizedDescription 产品描述信息：%@", [pro localizedDescription]);
        NSLog(@"price 价格：%@", [pro price]);
        NSLog(@"productIdentifier Product id：%@", [pro productIdentifier]);
        
        if([pro.productIdentifier isEqualToString: _productID]){
            p = pro;
        }
    }
    
    if(p){
        SKPayment *payment = [SKPayment paymentWithProduct:p];
        NSLog(@"发送购买请求");
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }else{
        HIDE_HUD;
        SHOW_HUD_MESSAGE(HH_LOC_STR(@"transaction failed!"));
    }
}



-(void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    NSLog(@"------------------错误 产品请求失败-----------------:%@", error);
    HIDE_HUD;
    SHOW_HUD_MESSAGE(HH_LOC_STR(@"transaction failed!"));
}

-(void)requestDidFinish:(SKRequest *)request{
    
}

- (void) paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        HIDE_HUD;
    });
    
    NSLog(@"%d",queue.transactions.count);
    NSLog(@"paymentQueueRestoreCompletedTransactionsFinished");
}

#pragma mark 监听购买结果
-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions{
    for (SKPaymentTransaction *transaction in transactions){
        NSLog(@"---------%@",transaction.error);
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased:{
                NSLog(@"-----交易完成 --------");
                
                [self completeTransaction:transaction];
            }
                break;
            case SKPaymentTransactionStateFailed:{
                NSLog(@"-----交易失败 --------");
                HIDE_HUD;
                SHOW_HUD_MESSAGE(HH_LOC_STR(@"transaction failed!"));
             [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
            }
                break;
            case SKPaymentTransactionStateRestored:{
                NSLog(@"-----已经购买过该商品(重复支付) --------");
                [self completeTransaction:transaction];
            }
            case SKPaymentTransactionStatePurchasing:  {
                NSLog(@"-----商品添加进列表 --------");
            }
                break;
            case SKPaymentTransactionStateDeferred:{
                NSLog(@"-----交易延迟 --------");
                HIDE_HUD;
                SHOW_HUD_MESSAGE(HH_LOC_STR(@"transaction failed!"));
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
            }
                break;
            default:
                break;
        }
    }
    
    
    
    
}

#pragma mark 购买成功
-(void)completeTransaction:(SKPaymentTransaction *)transaction{
    NSString *productID = transaction.payment.productIdentifier;
    NSLog(@"----------购买成功%@",productID);
    
    __weak typeof(self) weakSelf = self;
    if([productID isEqualToString:PRODUCT_ID_30_COINS]){
        [[UserInfoManger shared]addCoins:@(30) complete:^(BOOL success, NSString *error) {
            [weakSelf refreshViews];
            
            SHOW_HUD_MESSAGE(HH_LOC_STR(@"Purchase success, coins +30"));
        }];
    }
    
    
    if([productID isEqualToString:PRODUCT_ID_200_COINS]){
        __weak typeof(self) weakSelf = self;
        [[UserInfoManger shared]addCoins:@(200) complete:^(BOOL success, NSString *error) {
            [weakSelf refreshViews];
            SHOW_HUD_MESSAGE(HH_LOC_STR(@"Purchase success, coins +200"));
        }];
    }
    
    HIDE_HUD;
    if([productID isEqualToString:PRODUCT_ID_REMOVE_AD]){
        NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
        [de setBool:true forKey:IS_REMOVE_ADS_KEY];
        [self refreshViews];
        SHOW_HUD_MESSAGE(HH_LOC_STR(@"he ad has been removed and the restart app takes effect"));
    }
    
    

    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

#pragma mark 激励广告
- (IBAction)onWatchAD:(id)sender {
    if ([[GADRewardBasedVideoAd sharedInstance] isReady]) {
        [[GADRewardBasedVideoAd sharedInstance] presentFromRootViewController:self];
        _shouldRewardUser = false;
    }else{
        SHOW_HUD_MESSAGE(HH_LOC_STR(@"The ad is loading. Please try again later!"));
    }
    
    
    
}

#pragma mark 激励广告delegate
- (void)rewardBasedVideoAd:(GADRewardBasedVideoAd *)rewardBasedVideoAd
   didRewardUserWithReward:(GADAdReward *)reward {
    NSString * rewardMessage =
    [NSString stringWithFormat:@"Reward received with currency %@ , amount %lf",
     reward.type,
     [reward.amount doubleValue]];
    NSLog(@"%@", rewardMessage);
    
    _shouldRewardUser = true;
    __weak typeof(self) weakSelf = self;
    [[UserInfoManger shared]addCoins:@(10) complete:^(BOOL success, NSString *error) {
        
        if(success){
            [weakSelf refreshViews];
        }
        
        
    }];
}

- (void)rewardBasedVideoAdDidReceiveAd:(GADRewardBasedVideoAd *)rewardBasedVideoAd {
    NSLog(@"Reward based video ad is received.");
}

- (void)rewardBasedVideoAdDidOpen:(GADRewardBasedVideoAd *)rewardBasedVideoAd {
    NSLog(@"Opened reward based video ad.");
}

- (void)rewardBasedVideoAdDidStartPlaying:(GADRewardBasedVideoAd *)rewardBasedVideoAd {
    NSLog(@"Reward based video ad started playing.");
}

- (void)rewardBasedVideoAdDidClose:(GADRewardBasedVideoAd *)rewardBasedVideoAd {
    NSLog(@"Reward based video ad is closed.");
    
    if(_shouldRewardUser){
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:KNSLocal(@"alertTitle") message:HH_LOC_STR(@"You got 10 coins") delegate:self cancelButtonTitle:nil otherButtonTitles:KNSLocal(@"alertOK"), nil];
        
        [alert show];
    }
    
    [[GADRewardBasedVideoAd sharedInstance] loadRequest:[GADRequest request]
                                           withAdUnitID:@"ca-app-pub-1438263689659228/6329445499"];//激励视频广告
    
}

- (void)rewardBasedVideoAdWillLeaveApplication:(GADRewardBasedVideoAd *)rewardBasedVideoAd {
    NSLog(@"Reward based video ad will leave application.");
}

- (void)rewardBasedVideoAd:(GADRewardBasedVideoAd *)rewardBasedVideoAd
    didFailToLoadWithError:(NSError *)error {
    NSLog(@"Reward based video ad failed to load.");
    [[GADRewardBasedVideoAd sharedInstance] loadRequest:[GADRequest request]
                                           withAdUnitID:@"ca-app-pub-1438263689659228/6329445499"];//激励视频广告
}



- (IBAction)onCancel:(id)sender {
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
    [self dismissViewControllerAnimated:true completion:nil];
}

@end
